package com.pig4cloud.pig.ads.controller;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.google.common.collect.Lists;
import com.pig4cloud.pig.ads.pig.mapper.AdVideoMapper;
import com.pig4cloud.pig.ads.pig.mapper.PictureMapper;
import com.pig4cloud.pig.api.dto.AdPlanPictureLibDto;
import com.pig4cloud.pig.api.dto.PictureLibDto;
import com.pig4cloud.pig.api.dto.UpdatePicTypeDto;
import com.pig4cloud.pig.api.entity.PictureLib;
import com.pig4cloud.pig.api.vo.PictureLibVo;
import com.pig4cloud.pig.ads.service.AdvService;
import com.pig4cloud.pig.ads.service.PictureService;
import com.pig4cloud.pig.common.core.constant.enums.PlatformTypeEnum;
import com.pig4cloud.pig.common.core.util.R;
import com.pig4cloud.pig.common.security.util.SecurityUtils;
import io.swagger.annotations.Api;
import lombok.RequiredArgsConstructor;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.validation.Valid;
import java.util.*;

/**
 * @description:
 * @author: nml
 * @time: 2020/10/29 19:02
 **/

@RestController
@RequiredArgsConstructor
@RequestMapping("/picture")
@Api(value = "picture", tags = "图片库管理模块")
public class PictureController {
	@Autowired
	private final PictureService pictureService;

	@Autowired
	private final PictureMapper pictureMapper;

	private final AdVideoMapper adVideoMapper;

	private final AdvService advService;

	private static final Logger logger = LoggerFactory.getLogger(PictureController.class);

	//广点通：广告创意选择图片库的一张图片：判断是否推送。未推送就推送到广点通
	@RequestMapping("/oneFileSynGdt")
	public R oneFileSynGdt(PictureLibVo req) {
		if (null == req) {
			return R.failed("请选择一张图片！");
		}
		return pictureService.oneFileSynGdt(req);
	}

	//广点通：广告创意选择图片库的一张图片：判断是否推送。未推送就推送到头条

	@RequestMapping("/oneFileSyn")
	public R oneFileSyn(PictureLibVo req) {
		if (null == req) {
			return R.failed("请选择一张图片！");
		}
		return pictureService.oneFileSyn(req);
	}

	@RequestMapping("/findByIds")
	public R getByImageId(String platformPictureIds) {
		AdPlanPictureLibDto adPlanPictureLibDto = new AdPlanPictureLibDto();
		if (StringUtils.isBlank(platformPictureIds)) {
			return R.ok(adPlanPictureLibDto);
		}
		adPlanPictureLibDto = pictureMapper.selectByKey(platformPictureIds);
		if (Objects.isNull(adPlanPictureLibDto)) {
			return R.failed("投放平台上传图片信息表无此图片");
		}
		return R.ok(adPlanPictureLibDto);
	}

	/*@RequestMapping("/findByIds")
	public R getByImageId(String[] platformPictureIds ) {
		List<AdPlanPictureLibDto> AdPlanPictureLibDtoList= Lists.newArrayList();
		if(platformPictureIds == null || platformPictureIds.length == 0){
			return R.ok(AdPlanPictureLibDtoList);
		}
		for (String platformPictureId : platformPictureIds) {
			AdPlanPictureLibDto adPlanPictureLibDto = pictureMapper.selectByKey(platformPictureId);
			if (Objects.isNull(adPlanPictureLibDto)){
				return R.failed("投放平台上传图片信息表无此图片");
			}
			AdPlanPictureLibDtoList.add(adPlanPictureLibDto);
		}
		return R.ok(AdPlanPictureLibDtoList);
	}*/
	//图片上传及保存到数据库
	@RequestMapping("/filesUpload")
	//requestParam要写才知道是前台的那个数组
	public R filesUpload(MultipartFile[] file) {
		if (null == file) {
			//如果没有上传图片
			return R.ok(0, "请上传图片");
		}
		if (file.length <= 0) {
			//如果没有上传图片
			return R.ok(0, "请上传图片");
		}
		//验证前端图片数量<=20
		if (file.length > 20) {
			return R.failed("图片数量不能超过20张");
		}
		return pictureService.filesUpload(file);
	}


	/**
	 * 根据图片类型和选择的 广告账号id 入参来分页查询图片
	 *
	 * @param req
	 * @return
	 */
	@RequestMapping("/findAdPlanPicPage")
	public R findAdPlanPicPage(PictureLibVo req) {
		//设置分页条件
		Page page = new Page();
		page.setSize(req.getSize());
		page.setCurrent(req.getCurrent());
		if (StringUtils.isBlank(req.getAdvertiserId())) {
			return R.failed("请选择广告账户id");
		}
		IPage<AdPlanPictureLibDto> data = pictureMapper.selectAdPlanPicListPage(req);
		return R.ok(data, "请求成功");
	}

	/**
	 * 分页+ 同步状态列表
	 *
	 * @param req
	 * @return
	 */
	@RequestMapping("/findPage")
	public R findPage(PictureLibVo req) {
		//设置分页条件
		Page page = new Page();
		page.setSize(req.getSize());
		page.setCurrent(req.getCurrent());

		Map<String, Object> param = new HashMap<String, Object>();
		param.put("userId", SecurityUtils.getUser().getId());
		List<String> adList = Lists.newArrayList();


		//!!!获取当前账户下的广告账户集合
		Integer userId = SecurityUtils.getUser().getId();
		List<String> gdtAdvList = advService.getOwnerAdv(userId, PlatformTypeEnum.GDT.getValue());
		List<String> ttAdvList = advService.getOwnerAdv(userId, PlatformTypeEnum.TT.getValue());
		req.setGdtAdverList(gdtAdvList);//设置广点通广告账户列表
		req.setTtAdverList(ttAdvList);//设置头条广告账户列表
		adList.addAll(gdtAdvList);
		adList.addAll(ttAdvList);

		//分页查询图片列表
		req.setAdList(adList);
		req.setCreator(String.valueOf(SecurityUtils.getUser().getId()));
		if(StringUtils.isNotEmpty(req.getLabelname())){
			req.setLabelname("%"+req.getLabelname()+"%");
		}
		IPage<PictureLibDto> data = pictureMapper.selectAdPicListPage(req);

		//设置每条记录的ttId、gdtId
		List<PictureLibDto> records = data.getRecords();
		if (!records.isEmpty()) {
			//遍历每条图片记录
			for (int i = 0; i < records.size(); i++) {
				//1、设置推送状态灯
				Long ttId = records.get(i).getTtId();
				int ttSize = ttAdvList.size();
				if (ttSize > 0) {
					if (ttId == ttSize) {
						ttId = 2L;
					} else if (0 < ttId && ttId < ttSize) {
						ttId = 1L;
					}
					records.get(i).setTtId(ttId);
				}

				Long gdtId = records.get(i).getGdtId();
				int gdtSize = gdtAdvList.size();
				if (gdtSize > 0) {
					if (gdtId == gdtSize) {
						gdtId = 2L;
					} else if (0 < gdtId && gdtId < gdtSize) {
						gdtId = 1L;
					}
					records.get(i).setGdtId(gdtId);
				}

				//2、当前账号的广告账户列表推送状态
				//广点通
				List<Map<String, String>> pushGdtAdStatusList = Lists.newArrayList();
				if (gdtAdvList != null && !gdtAdvList.isEmpty()) {
					String gdtAdvertiserIds = records.get(i).getGdtAdvertiserIds();
					for (int j = 0; j < gdtAdvList.size(); j++) {
						Map<String, String> pushGdtAdStatus = new HashMap();
						String adv = gdtAdvList.get(j);
						if (StringUtils.isNotBlank(gdtAdvertiserIds) && gdtAdvertiserIds.contains(adv)) {
							pushGdtAdStatus.put("advertiserId", adv);
							pushGdtAdStatus.put("pushStatus", "1");
						} else {
							pushGdtAdStatus.put("advertiserId", adv);
							pushGdtAdStatus.put("pushStatus", "0");
						}
						pushGdtAdStatusList.add(pushGdtAdStatus);
					}
				}
				records.get(i).setPushGdtAdStatusList(pushGdtAdStatusList);
				//头条
				List<Map<String, String>> pushTtAdStatusList = Lists.newArrayList();
				if (ttAdvList != null && !ttAdvList.isEmpty()) {
					String ttAdvertiserIds = records.get(i).getTtAdvertiserIds();
					for (int j = 0; j < ttAdvList.size(); j++) {
						Map<String, String> pushTtAdStatus = new HashMap();
						String adv = ttAdvList.get(j);
						if (StringUtils.isNotBlank(ttAdvertiserIds) && ttAdvertiserIds.contains(adv)) {
							pushTtAdStatus.put("advertiserId", adv);
							pushTtAdStatus.put("pushStatus", "1");
						} else {
							pushTtAdStatus.put("advertiserId", adv);
							pushTtAdStatus.put("pushStatus", "0");
						}
						pushTtAdStatusList.add(pushTtAdStatus);
					}
				}
				records.get(i).setPushTtAdStatusList(pushTtAdStatusList);

			}
			data.setRecords(records);
		}

		return R.ok(data, "请求成功");
	}

	@RequestMapping("/findById")
	public R getById(Integer id) {
		PictureLib pictureLib = pictureMapper.selectByPrimaryKey(id);
		return R.ok(pictureLib, "操作成功");
	}

	/**
	 *修改类型
	 */
	@PostMapping(value = "/updateType")
	public R updateType(@RequestBody @Valid UpdatePicTypeDto updatePicTypeDto, BindingResult bindingResult){
		if(bindingResult.hasErrors()){
			return R.failed(bindingResult.getFieldError().getDefaultMessage());
		}
		return pictureService.updatePType(updatePicTypeDto);
	}

	//删除图片或批量删除图片
	@RequestMapping("/delOneOrBatch")
	public R delOneOrBatch(PictureLibVo pictureLibVo) {
		return pictureService.delSelective(pictureLibVo);
	}

	@RequestMapping("/modify")
	public R modify(PictureLib pictureLib) {
		return pictureService.updateSelective(pictureLib);
	}

	/**
	 * 设置封面
	 *
	 * @param pictureLib
	 * @return
	 */
	@RequestMapping("/editCover")
	public R editCover(PictureLib pictureLib) {
		try {
			PictureLib picture = pictureService.getById(pictureLib.getId());
			if (null != picture) {
				//重置该视频封面
				PictureLib vo = new PictureLib();
				vo.setIsCover(0);
				pictureService.update(vo, Wrappers.<PictureLib>query().lambda().eq(PictureLib::getVideoId, picture.getVideoId()));
				//设置当前图片为封面
				vo.setIsCover(1);
				pictureService.update(vo, Wrappers.<PictureLib>query().lambda().eq(PictureLib::getId, picture.getId()));
				return R.ok(null, "操作成功");
			} else {
				return R.failed(null, "图片ID无效");
			}
		} catch (Exception e) {
			e.printStackTrace();
			return R.failed(null, "操作失败");
		}
	}


}
